# -*- coding: utf-8 -*-
import threading
from dateutil import tz
from datetime import datetime, timedelta
from scrapy.utils.project import get_project_settings
from zc_core.util.common import parse_date


class OrderItemFilter(object):
    """
    已采集商品过滤器
    用于全量商品明细重复采集时，过滤已采过的商品，避免重复采集
    """
    _instance_lock = threading.Lock()
    _biz_inited = False

    def __new__(cls, *args, **kwargs):
        if not hasattr(OrderItemFilter, "_instance"):
            with OrderItemFilter._instance_lock:
                if not hasattr(OrderItemFilter, "_instance"):
                    OrderItemFilter._instance = object.__new__(cls)
        return OrderItemFilter._instance

    def __init__(self):
        if not self._biz_inited:
            settings = get_project_settings()
            self._biz_inited = True
            # 截止日期
            if settings.get('ORDER_DEADLINE_DAYS', None):
                days = settings.getint('ORDER_DEADLINE_DAYS', 60)
                self.deadline = datetime.now(tz.gettz('Asia/Shanghai')) - timedelta(days=days)
            else:
                self.deadline = parse_date(settings.get('ORDER_DEADLINE', '2019-01-01'))

    def to_save(self, order_time):
        if order_time < self.deadline:
            return False

        return True

    def get_deadline(self):
        return self.deadline
